<?php

class Application_Model_CartMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Cart');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Cart $cart){
		$data = array(
				'checked_out' => $cart->getChecked_out(),
		);
	
		if (null === ($id = $cart->getId())) {
			unset($data['id_cart']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_cart = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Cart $cart){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$cart->setId($row->id_cart)
			->setChecked_out($row->checked_out);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Cart();
			$entry->setId($row->id_cart)
				->setChecked_out($row->checked_out);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function delete($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_cart = ?', $id);
		return $this->getDbTable()->delete($where);
	}
}

